<?php
error_reporting(E_ALL);
include('./config.php');
error_reporting(E_ALL);

$startdate = '1984-01-01';
//$enddate = '1984-12-31';
$enddate = '2005-12-31';
$cache_date = '2010-10-18 12:00:00';
// specify max models to run at a time
$max_simultaneous = 7;
$scid = 28;
$params = '';
$delimiter = ',';

if (isset($argv[1])) {
   $elementid = $argv[1];
} else {
   $elementid = -1;
}
if (isset($argv[2])) {
   $variables = $argv[2];
} else {
   $variables = 'Qout';
}
if (isset($argv[3])) {
   $runid = $argv[3];
} else {
   $runid = -1;
}
if (isset($argv[4])) {
   $startdate = $argv[4];
} else {
   $startdate = '';
}
if (isset($argv[5])) {
   $enddate = $argv[5];
} else {
   $enddate = '';
}
$operation = 2;
if (isset($_GET['elementid'])) {
   $elementid = $_GET['elementid'];
}
if (isset($_GET['variables'])) {
   $variables = $_GET['variables'];
}
if (isset($_GET['operation'])) {
   $operation = $_GET['operation'];
}
if (isset($_GET['runid'])) {
   $runid = $_GET['runid'];
}
if (isset($_GET['delimiter'])) {
   $delimiter = $_GET['delimiter'];
   switch ($delimiter) {
      case '\t':
         $delimiter = "\t";
      break;
      case 'tab':
         $delimiter = "\t";
      break;
      case 'comma':
         $delimiter = ",";
      break;
      case 'pipe':
         $delimiter = "|";
      break;
      
      default:
      break;
   }
}
if (isset($_GET['startdate'])) {
   $startdate = $_GET['startdate'];
} 
if (isset($_GET['enddate'])) {
   $enddate = $_GET['enddate'];
} 
if (isset($_GET['params'])) {
   $params = $_GET['params'];
} 
if (isset($_GET['querytype'])) {
   $querytype = $_GET['querytype'];
} 
$title_column = 'elementid';
if (isset($_GET['title_column'])) {
   $title_column = $_GET['title_column'];
} 
if (isset($_GET['header'])) {
   $header = $_GET['header'];
}  else {
   $header = 1;
}
if (isset($_GET['debug'])) {
   $debug = $_GET['debug'];
}  else {
   $debug = 0;
}

// drupal feed specific
if (isset($_GET['scenarioid'])) {
   $scenarioid = $_GET['scenarioid'];
} 
if (isset($_GET['node_scenarioid'])) {
   $node_scenarioid = $_GET['node_scenarioid'];
} 
$extras = array();
if (isset($_GET['objectclass'])) {
   $objectclass = $_GET['objectclass'];
   $extras['objectclass'] = $objectclass;
} 
if (isset($_GET['custom1'])) {
   $custom1 = $_GET['custom1'];
   $extras['custom1'] = $custom1;
} 
if (isset($_GET['custom2'])) {
   $custom2 = $_GET['custom2'];
   $extras['custom2'] = $custom2;
} 


if (isset($_GET['date_type'])) {
   switch ($_GET['date_type']) {
      case 'matlab':
      $date_format = 'MM/DD/YYYY';
      break;
      
      default:
      $date_format = '';
      break;
   }
}

switch ($operation) {

   case 1:
   // show the value of requested parameters as a text file
   $output = '';
   $ld = '';
   $loadres = loadModelElement($elementid, array(), 1);
   if (is_object($loadres['object'])) {
      $thisobject = $loadres['object'];
      foreach (split(',',$variables) as $thisvar) {
         if ($params == '') {
            error_log("Calling getProp($thisvar) \n");
            if ($debug) {
               print("Calling getProp($thisvar) on elementid = $elementid<br>");
            }
            $thisval = $thisobject->getProp($thisvar);
         } else {
            error_log("Calling showElementInfo($thisvar, $params) \n");
            if ($debug) {
               print("Calling showElementInfo($thisvar, $params) <br>");
            }
            $thisval = $thisobject->showElementInfo($thisvar, $params);
         }
         $output .= $ld . $thisval;
         $ld = "\n";
      }
   }
   print($output);
   break;

   case 2:
   $result = compareRunData($elementid, $runid, $variables, $startdate, $enddate, 1, $debug, array(), 'left outer', $date_format);
   $query = $result['query'];
   if ($debug) {
      print($result['error'] . "<br>\n");
   }
   //print("Date Format: $date_format $query\n");
   if (count($result['records']) > 0) {
      $header = implode($delimiter, array_keys($result['records'][0]));
      print("$header\r\n");
      foreach ($result['records'] as $thisrec) {
         $line = implode($delimiter, array_values($thisrec));
         print("$line\r\n");
      }
   }
   break;
   
   case 3:
   // get model results from the scen_model_run_data table vin CSV format
   $varlist = "'" . implode("','", explode(",",$variables)) . "'";
   $listobject->querystring = "  select md5(elementid::varchar || runid::varchar || dataname ) as data_hash, * from scen_model_run_data ";
   $listobject->querystring .= " where ( ( elementid in ($elementid) ) or ('$elementid' = '-1') ) ";
   $listobject->querystring .= "    and ( (dataname in ($varlist)) or ('$dataname' = '') )";
   $listobject->querystring .= "    and ( ( runid in ($runid) ) or ('$runid' = '-1') ) ";
   if (isset($scenarioid)) {
      $listobject->querystring .= "    and ( elementid in (select elementid from scen_model_element where scenarioid = $scenarioid )) ";
   }
   //print($listobject->querystring . "<br>");
   $listobject->performQuery();
   if ($listobject->numrows > 0) {
      $header = implode($delimiter, array_keys($listobject->queryrecords[0]));
      print("$header\r\n");
      foreach ($listobject->queryrecords as $thisrec) {
         $line = implode($delimiter, array_values($thisrec));
         print("$line\r\n");
      }
   }
   break;
   
   case 4:
   // get model results from the scen_model_run_data table vin CSV format
   $objectclasslist = "'" . implode("','", explode(",",$objectclass)) . "'";
   $custom1list = "'" . implode("','", explode(",",$custom1)) . "'";
   $custom2list = "'" . implode("','", explode(",",$custom2)) . "'";
   $titlist = implode("::varchar || ' ' ||", explode(",",$title_column)) . "::varchar";
   $listobject->querystring = "  select $titlist as element_title, elementid, scenarioid, elemname, objectclass, custom1, custom2 from scen_model_element ";
   $listobject->querystring .= " where ( ( elementid in ($elementid) ) or ('$elementid' = '-1') ) ";
   $listobject->querystring .= "    and ( ( scenarioid in ($scenarioid) ) or ('$scenarioid' = '-1') ) ";
   $listobject->querystring .= "    and ( ( custom1 in ($custom1list) ) or ($custom1list = '') ) ";
   $listobject->querystring .= "    and ( ( custom2 in ($custom2list) ) or ($custom2list = '') ) ";
   $listobject->querystring .= "    and ( ( objectclass in ($objectclasslist) ) or ($objectclasslist = '') ) ";
   //print($listobject->querystring . "<br>");
   $listobject->performQuery();
   if ($listobject->numrows > 0) {
      $header = implode($delimiter, array_keys($listobject->queryrecords[0]));
      print("$header\r\n");
      foreach ($listobject->queryrecords as $thisrec) {
         $line = implode($delimiter, array_values($thisrec));
         print("$line\r\n");
      }
   }
   break;
   
   case 5:
   $varlist = "'" . implode("','", explode(",",$variables)) . "'";
   $listobject->querystring = "  select a.elementid from scen_model_element as a, scen_model_element as b ";
   $listobject->querystring .= " where b.elementid = $elementid  ";
   $listobject->querystring .= "    and contains( a.poly_geom, b.point_geom )";
   $listobject->querystring .= "    and a.custom1 in ('cova_ws_subnodal', 'cova_ws_container') ";
   $listobject->querystring .= "    and a.scenarioid = $scenarioid ";
   $listobject->querystring .= "    and b.scenarioid = $node_scenarioid ";
   //print($listobject->querystring . "<br>");
   $listobject->performQuery();
   if ($listobject->numrows > 0) {
      $parentid = $listobject->getRecordValue(1,'elementid');
   } else {
      $parentid = -1;
   }
   print("$parentid\r\n");
   break;
   
   case 6:
   // get an elements name
   $varlist = "'" . implode("','", explode(",",$variables)) . "'";
   $listobject->querystring = "  select a.elemname from scen_model_element as a ";
   $listobject->querystring .= " where a.elementid = $elementid  ";
   //print($listobject->querystring . "<br>");
   $listobject->performQuery();
   if ($listobject->numrows > 0) {
      $elemname = $listobject->getRecordValue(1,'elemname');
   } else {
      $elemname = -1;
   }
   print("$elemname\r\n");
   break;
   
   case 7:
   // do a vahydro element query
   // Requires: querytype, scenarioid, variables
   // Optional: custom1, custom2, objectclass, params
   $known_vars = array();
   $known_vars['elemname'] = array('table' => 'scen_model_element');
   $known_vars['elementid'] = array('table' => 'scen_model_element');
   $known_vars['custom1'] = array('table' => 'scen_model_element');
   $known_vars['custom2'] = array('table' => 'scen_model_element');
   $known_vars['huc'] = array('table' => 'huc_va');
   $query_vars = array();
   $varlist = explode(",",$variables);
   foreach ($varlist as $thisvar) {
      if (in_array($thisvar, array_keys($known_vars))) {
         $query_vars[] = $thisvar;
      }
   }
   $paramlist = explode(",",$params);
   $known_queries = array();
   $tables = array('scen_model_element');
   $qv_formatted = array();
   foreach ($query_vars as $vname) {
      if (isset($known_vars[$vname])) {
         $qv_formatted[] = $known_vars[$vname]['table'] . '."' . $vname . '"';
         if (!in_array($known_vars[$vname]['table'], $tables)) {
            $tables[] = $known_vars[$vname]['table'];
         }
      } else {
         $qv_formatted[] = 'scen_model_element."' . $vname . '"';
      }
   }
   $varsql = implode(", ", $qv_formatted);
   
   $known_queries['cbp_major'] = array('where' => "( substring(scen_model_element.custom2, 1, 1) = '$params' )" );
   $known_queries['cbp_minor'] = array('where' => "( substring(scen_model_element.custom2, 1, 2) = '$params' )" );
   $known_queries['custom2'] = array('where' => "( scen_model_element.custom2 = '$params' )" );
   $known_queries['elementid'] = array('where' => "( scen_model_element.elementid = '$params' )" );
   $known_queries['huc8'] = array('table' => 'huc_va', 'where' => "( huc_va.huc = '$params' ) " );
   
   $wparms = array(" ( scenarioid = $scenarioid ) ");
   if (isset($known_queries[$querytype])) {
      $wparms[] = $known_queries[$querytype]['where'];
      if (isset($known_queries[$querytype]['table'])) {
         if (!in_array($known_queries[$querytype]['table'], $tables)) {
            $tables[] = $known_queries[$querytype]['table'];
         }
      }
   }
   foreach ($extras as $thiscol => $thisext) {
      if (count(explode(",", $thisext)) > 1) {
         $options = explode(",", $thisext);
         $wparms[] = "($thiscol in ( '" . implode("', '", $options) . "') )";
      } else {
         $wparms[] = "($thiscol = '$thisext')";
      }
   }
   //$listobject->querystring = "  select $varsql from " . implode(", ", $tables);
   $listobject->querystring = "  select $varsql ";
   $listobject->querystring .= "  from scen_model_element ";
   if ($querytype == 'huc8') {
      $listobject->querystring .= "  left outer join huc_va on (CASE WHEN scen_model_element.geomtype = 1 THEN contains(huc_va.the_geom, scen_model_element.point_geom) ";
      $listobject->querystring .= "WHEN scen_model_element.geomtype = 2 THEN (huc_va.the_geom && scen_model_element.line_geom) ";
      $listobject->querystring .= "WHEN scen_model_element.geomtype = 3 THEN contains(huc_va.the_geom, st_PointOnSurface(scen_model_element.poly_geom) ) ";
      $listobject->querystring .= "ELSE FALSE END) ";
   }
   $listobject->querystring .= " where " . implode(' AND ', $wparms);
   $listobject->querystring .= " group by  $varsql ";
   if ($debug) {
      print($listobject->querystring . "<br>");
   }
   
   $listobject->performQuery();
   if ($listobject->numrows > 0) {
      if ($header) {
         $header = implode($delimiter, array_keys($listobject->queryrecords[0]));
         print("$header\r\n");
      }
      foreach ($listobject->queryrecords as $thisrec) {
         $line = implode($delimiter, array_values($thisrec));
         print("$line\r\n");
         if ($debug) {
            print("<br>");
         }
      }
   }
   
   break;

   default:
   $result = compareRunData($elementid, $runid, $variables, $startdate, $enddate, 1, $debug, array(), 'left outer', $date_format);
   $query = $result['query'];
   print("$query\n");
   if (count($result['records']) > 0) {
      $header = implode($delimiter, array_keys($result['records'][0]));
      print("$header\r\n");
      foreach ($result['records'] as $thisrec) {
         $line = implode($delimiter, array_values($thisrec));
         print("$line\r\n");
      }
   }
   break;

}
?>